<template>
  <div>
    <div class="flex mb10 justify-end">
      <el-input-number v-model="line" class="mr10" :min="1" />
      <el-button type="primary" @click="scrollTable">滚动到第{{ line }}行</el-button>
    </div>
    <el-table ref="elTable" :data="tableData" border style="width: 100%" :height="tableHeight">
      <el-table-column prop="id" label="ID" width="180" />
      <el-table-column prop="date" label="日期" width="180" />
      <el-table-column prop="name" label="姓名" width="180" />
      <el-table-column prop="address" label="地址" />
    </el-table>
  </div>
</template>

<script>
export default {
  data() {
    return {
      line: 1,
      tableHeight: 580,
      tableData: []
    }
  },
  created() {
    this.getData()
  },
  mounted() {
    window.addEventListener('resize', this.getNewTableHeight)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.getNewTableHeight)
  },
  methods: {
    scrollTable() {
      if (this.line > this.tableData.length) return this.$message.warning('超出数据范围')

      const tableBodyWrapper = this.$refs.elTable.bodyWrapper
      tableBodyWrapper.scrollTop = 0
      const tableItems = document.getElementsByClassName('el-table__row')
      const tableTop = tableBodyWrapper.getBoundingClientRect().top
      const tableItemTop = tableItems[this.line - 1].getBoundingClientRect().top
      const scrollTop = tableItemTop - tableTop

      if (tableBodyWrapper) {
        // 表格滚动
        tableBodyWrapper.scrollTop = scrollTop
      }
    },
    getNewTableHeight() {
      this.tableHeight = document.documentElement.clientHeight / (695 / 580)
    },
    getData() {
      const newTableData = []
      for (let index = 0; index < 100; index++) {
        let address = ''
        if (index % 2 === 0) {
          address = '上海市普陀区金沙江路 1518 弄'
        } else {
          address =
            '上海市普陀区金沙江路 1517 弄上海市普陀区金沙江路 1517 弄上海市普陀区金沙江路 1517 弄上海市普陀区金沙江路 1517 弄上海市普陀区金沙江路 1517 弄上海市普陀区金沙江路 1517 弄上海市普陀区金沙江路 1517 弄上海市普陀区金沙江路 1517 弄上海市普陀区金沙江路 1517 弄'
        }
        newTableData.push({
          id: index + 1,
          date: '2016-05-02',
          name: '王小虎',
          address
        })
      }
      this.tableData = newTableData
    }
  }
}
</script>

<style lang="scss" scoped>
.flex {
  display: flex;
}
.justify-end {
  justify-content: flex-end;
}

.mr10 {
  margin-right: 10px;
}

.mb10 {
  margin-bottom: 10px;
}
</style>
